const Koa = require('koa');
const KoaWebSocket = require('koa-websocket');
const Router = require('koa-router');
const app = KoaWebSocket(new Koa());
const router = new Router();

// WebSocket 路由
router.get('/ws', (ctx) => {
  console.log('WebSocket connected');

  // 监听客户端消息
  ctx.websocket.on('message', (message) => {
    console.log('Received message:', message);
  });

  // 模拟实时数据推送
  const interval = setInterval(() => {
    const data = generateEChartsData(); // 生成 ECharts 数据
    console.log(data);
    
    ctx.websocket.send(JSON.stringify(data)); // 发送数据
  }, 10000);

  // 监听连接关闭
  ctx.websocket.on('close', () => {
    console.log('WebSocket disconnected');
    clearInterval(interval); // 清除定时器
  });
});

// 注册 WebSocket 路由
app.ws.use(router.routes()).use(router.allowedMethods());

// 生成 ECharts 数据
function generateEChartsData() {
  return {
    xAxis: {
      type: 'category',
      data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
    },
    yAxis: {
      type: 'value',
    },
    series: [
      {
        data: [Math.random() * 100, Math.random() * 100, Math.random() * 100, Math.random() * 100, Math.random() * 100, Math.random() * 100, Math.random() * 100],
        type: 'line',
      },
    ],
  };
}

// 启动服务器
app.listen(3000, () => {
  console.log('Server is running on http://localhost:3000');
});